package commRedisStatus

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"time"
)

const (
	keySync = "fox-edge:service:status:sync"
	keyData = "fox-edge:service:status:data"
)

const (
	keyActiveTime      = "activeTime"
	keyServiceType     = "serviceType"
	keyServiceName     = "serviceName"
	keyModelType       = "modelType"
	keyModelName       = "modelName"
	keyApplicationName = "applicationName"
	keyAppPort         = "appPort"
)

const (
	ModelTypeChannel = "channel"
	ModelTypeDevice  = "device"
	ModelNameDevice  = "device"
)

var (
	Producer *redisStatusProducerService
	Consumer *redisStatusConsumerService
)

func init() {
	Producer = &redisStatusProducerService{}
	Consumer = &redisStatusConsumerService{}

	Producer.values = make(map[string]interface{})
	Consumer.values = make(map[string]interface{})

}

func Instance() {
	// 2.初始化生产者：将redis的上次数据，再加上基础数据，保存到本地缓存
	initProducer()
}

func initProducer() {
	serviceKey := getServiceKey()
	values := Consumer.GetValues()

	// 在初始化阶段，从redis的数据中，继承原有数据，防止删除/添加造成的抖动现象
	val, ok := values[serviceKey]
	if ok {
		value := val.(map[string]interface{})
		Producer.append(value)
	}

	// 从redis中装载原有的数据，避免冲掉原来数据
	Producer.Load()

	// 填写部分字段的初始值
	Producer.SetValue(keyServiceType, commEnv.Service.ServiceType)
	Producer.SetValue(keyServiceName, commEnv.Service.ServiceName)
	Producer.SetValue(keyModelType, commEnv.Service.ModelType)
	Producer.SetValue(keyModelName, commEnv.Service.ModelName)
	Producer.SetValue(keyApplicationName, commEnv.Service.ApplicationName)
	Producer.SetValue(keyAppPort, commEnv.Service.AppPort)
}

// Scheduler 创建一个线程
func Scheduler() {
	go scheduler()
}

// 线程函数
func scheduler() {
	for true {
		// 装载数据
		Consumer.Load()

		// 更新时间
		Producer.SetValue(keyActiveTime, time.Now().UnixMilli())
		Producer.Save()

		time.Sleep(3 * time.Second)
	}
}

func getServiceKey() string {
	return BuildServiceKey(commEnv.Service.ServiceType, commEnv.Service.ServiceName)
}

func BuildServiceKey(serviceType, serviceName string) string {
	return "\"" + serviceType + ":" + serviceName + "\""
}
